package com.web.onirigi.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.web.onirigi.config.BaseConfig;
import com.web.onirigi.service.ImageService;
import com.web.onirigi.util.IdeaUtil;

import sun.misc.BASE64Decoder;

/**
 * 图片上传
 * @author fengruiqi
 *
 */
@Service
public class ImageServiceImpl implements ImageService {

	private Logger logger=LoggerFactory.getLogger(ImageServiceImpl.class);
	
	/**
	 * 图片保存基础路径
	 */
	@Value("${image.base.url}")
	public  String IMG_BASE_URL ;
	
	/**
	 * 图片保存路径
	 */
	@Value("${image.dir}")
	public  String IMAGE_DIR;
	
	
	@Override
	public String saveImage(MultipartFile file) throws IOException {
        int dotPos = file.getOriginalFilename().lastIndexOf(".");
        if (dotPos < 0) {
            return null;
        }
        String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
        if (!IdeaUtil.isFileAllowed(fileExt)) {
            return null;
        }

        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
        Files.copy(file.getInputStream(), new File(IMAGE_DIR + fileName).toPath(),
                StandardCopyOption.REPLACE_EXISTING);
        return IMG_BASE_URL + "image?name=" + fileName;
    }

	@Override
	public List<String> saveImages(MultipartFile[] files) throws IOException {
		List<String> list =new ArrayList<String>(); 
		for(MultipartFile file : files){
			int dotPos = file.getOriginalFilename().lastIndexOf(".");
			if (dotPos < 0) {
				return null;
			}
			String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
			if (!IdeaUtil.isFileAllowed(fileExt)) {
				return null;
			}
			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
			Files.copy(file.getInputStream(), new File(IMAGE_DIR + fileName).toPath(),
					StandardCopyOption.REPLACE_EXISTING);
			fileName= IMG_BASE_URL + "image?name=" + fileName;
			
			list.add(fileName);
		}
	
		return list;
	}

	
	
	
	
	/**
	 * 将图片进行 解码
	 * @author ASUS
	 * 创建时间  2017年10月8日 下午4:13:05
	 * @param imgStr
	 * @param imgFilePath
	 * @return
	 */
	public boolean string2Image(String imgStr, String imgFilePath) {  
		imgStr = imgStr.replaceAll("data:image/jpeg;base64,", ""); 
	    // 对字节数组字符串进行Base64解码并生成图片  
	    if (imgStr == null)  
	        return false;  
	    try {  
	        // Base64解码  
	        byte[] b = new BASE64Decoder().decodeBuffer(imgStr);  
	        for (int i = 0; i < b.length; ++i) {  
	            if (b[i] < 0) {  
	                // 调整异常数据  
	                b[i] += 256;  
	            }  
	        }  
	        File imageFile = new File(imgFilePath);
            imageFile.createNewFile();
            if(!imageFile.exists()){
               imageFile.createNewFile();
            }
	        // 生成Jpeg图片  
	        OutputStream out = new FileOutputStream(imageFile);  
	        out.write(b);  
	        out.flush();  
	        out.close();  
	        return true;  
	    } catch (Exception e) {  
	    	logger.error("图片保存错误",e);
	        return false;  
	    }  
	}
	
	
	@Override
	public String saveImageFromBase(String imgStr)  {
		String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "."+"jpeg" ;
		String path =IMAGE_DIR + fileName;
		if(this.string2Image(imgStr, path)) {
			fileName= IMG_BASE_URL + "image?name=" + fileName;
			return fileName;
		}else {
			return null;
		}
	}

	
	
}
